import random
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier



def Max_MinNormalization(data,Max,Min):
    data = (data - Min) / (Max - Min)
    return data
# 加载数据集
def loadDataset(filename, split):
    data = pd.read_excel(filename)
    data = np.array(data)
    data_list = data.tolist()
    # 0-20 A 0
    # 20-30 B 1
    # 30-40 C 2
    # 40-50 D 3
    # >=50 E 4

    xunliandata=[]
    train_lable=[]
    train_data=[]
    for i in data_list:
        # fabin.append(i[2])
        tt = []
        ttt = i[11:18]
        maxx = max(ttt)
        minn = min(ttt)
        for j in range(11, 18):
            # tt.append(Max_MinNormalization(i[j], maxx, minn))
            tt.append(i[j])
        if i[2] in range(0, 20):
            tt.append('A')
        if i[2] in range(20, 30):
            tt.append('B')
        if i[2] in range(30, 40):
            tt.append('C')
        if i[2] in range(40, 50):
            tt.append('D')
        if i[2] >= 50:
            tt.append('E')
        xunliandata.append(tt)

    dataset = xunliandata
    for x in range(len(dataset) - 1):
        if random.random() < split:  # 将数据集随机划分
            train_lable.append(dataset[x].pop())
            train_data.append(dataset[x])

    return train_data,train_lable
        # else:
        #     test_lable.append(dataset[x].pop())
        #     test_data.append(dataset[x])


# train_data,train_lable = loadDataset(r'data1.xlsx',1)
# test_data,test_lable = loadDataset(r'data_test.xlsx',1)
# knn = KNeighborsClassifier(n_neighbors=18)
# knn.fit(train_data,train_lable)
#
# from sklearn.externals import joblib
# joblib.dump(knn,'knn_predict.pkl')
# # knn=joblib.load('filename.pkl')
#
# assess_model_socre=knn.score(test_data,test_lable)
# print('KNN Test score:{:2f}'.format(assess_model_socre))

def getknndata(l):

    train_data,train_lable = loadDataset(r'./myApp/forecast/data.xlsx', 0.8)
    lis = []
    for i in l:
        lis.append(float(i))
    print(lis)
    knn = KNeighborsClassifier(n_neighbors=18)
    knn.fit(train_data, train_lable)
    return knn.predict([l])

